<template>
  <CustomDialog :drag-dialog="dialogInfo">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :disabled="!form.busPageInfo.editable"
      size="mini"
      label-width="160px"
    >
      <el-row :gutter="2">
        <el-col :span="8">
          <el-form-item label="物料类别" prop="busMainData.catId">
            <ItemCategoryTreeSelect
              v-model="form.busMainData.catId"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="物料编码" prop="busMainData.itemCode">
            <el-input v-model="maxItemCode" :disabled="!isAdd" />
          </el-form-item>
          <el-form-item label="物料名称" prop="busMainData.itemName">
            <el-input v-model="form.busMainData.itemName" />
          </el-form-item>
          <el-form-item label="规格" prop="busMainData.itemSpec">
            <el-input v-model="form.busMainData.itemSpec" />
          </el-form-item>
          <el-form-item label="客户编码" prop="busMainData.customCode">
            <el-input v-model="form.busMainData.customCode" />
          </el-form-item>
          <el-form-item label="品牌" prop="busMainData.itemBrand">
            <el-input v-model="form.busMainData.itemBrand" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存单位" prop="busMainData.stockUnit">
            <el-select
              v-model="form.busMainData.stockUnit"
              :style="style"
              filterable
              clearable
              placeholder="库存单位"
            >
              <el-option
                v-for="item in dicts.item_unit"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
            <el-button
              icon="el-icon-plus"
              title="点击添加单位转换率"
              @click="addItemUnitRate"
            />
            <item-unit-rate
              ref="itemUnitRate"
              :item-unit-rates="form.itemUnitRates"
              :stock-unit="form.busMainData.stockUnit"
            />
          </el-form-item>
          <el-form-item label="计价币别" prop="busMainData.priceCur">
            <el-select
              v-model="form.busMainData.priceCur"
              :style="style"
              filterable
              clearable
              placeholder="计价币别"
            >
              <el-option
                v-for="item in dicts.bus_price_cur"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="含税进货价" prop="busMainData.unitPrice">
            <el-input-number
              v-model.number="form.busMainData.unitPrice"
              :controls="false"
              :precision="6"
              :min="0"
              size="mini"
            />
          </el-form-item>
          <el-form-item label="默认存货仓库" prop="busMainData.warehouseId">
            <WarehouseTreeSelect
              v-model="form.busMainData.warehouseId"
              style="width: 200px"
            />
          </el-form-item>
          <el-input
            v-model="form.busMainData.storelocationName"
            style="width: 100%"
          >
            <el-button
              slot="append"
              icon="el-icon-plus"
              size="mini"
              title="点击选择库位"
              @click="doSelectSl()"
            />
          </el-input>
          <el-form-item label="会计科目" prop="busMainData.accountCode">
            <el-input v-model="form.busMainData.accountCode" />
          </el-form-item>
          <el-form-item label="安全库存" prop="busMainData.safetyStock">
            <el-input-number
              v-model.number="form.busMainData.safetyStock"
              :controls="false"
              :precision="2"
              :min="0"
              size="mini"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="图片">
            <FileUpload
              ref="imageFileUpload"
              :editable="form.busPageInfo.editable"
              :sup_this="sup_this"
              :file-limit="99"
              :is-direct-upload="true"
              list-type="avatar"
              accept=".jpg,.jpeg,.png"
              @fileRemoveSuccess="fileRemoveSuccess"
              @fileUploadSuccess="imageFileUploadSuccess"
            />
          </el-form-item>
          <el-form-item label="批号管理" prop="busMainData.lotType">
            <el-select
              v-model="form.busMainData.lotType"
              :style="style"
              placeholder="批号管理"
            >
              <el-option
                v-for="item in dicts.item_lot_type"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="默认税率" prop="busMainData.taxRate">
            <el-input-number
              v-model.number="form.busMainData.taxRate"
              :controls="false"
              :precision="2"
              :min="0"
              size="mini"
            />
          </el-form-item>
          <el-form-item label="物料属性" prop="busMainData.itemType">
            <el-select
              v-model="form.busMainData.itemType"
              :style="style"
              placeholder="物料属性"
            >
              <el-option
                v-for="item in dicts.item_type"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="销售品" prop="busMainData.saleFlag">
            <el-checkbox
              v-model="form.busMainData.saleFlag"
              true-label="Y"
              false-label="N"
            />
          </el-form-item>
          <el-form-item label="拼音简写" prop="busMainData.pinyin">
            <el-input v-model="form.busMainData.pinyin" size="mini" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs active-name="otherTab">
        <el-tab-pane name="otherTab" label="其它属性">
          <el-form-item label="默认供应商" prop="itemPurchase.supplyCpyCode">
            <template slot="label">
              默认供应商<IconHelp
                display-content="用于采购或外发赋值默认的供应商."
              />
            </template>
            <CpyOrgSetSelectDialog
              v-model="form.itemPurchase.supplyCpyName"
              :cpy-code="form.itemPurchase.supplyCpyCode"
              :ori-org-code="form.itemPurchase.supplyOrgCode"
              cpy-owner-type="supply"
              @cpySelectCallback="customSupplySelectCallback"
              @orgSetSelectCallback="orgSetSelectCallback"
            />
          </el-form-item>
          <el-form-item label="采购/生产部门" prop="itemPurchase.prodOrgCode">
            <template slot="label">
              采购/生产部门<IconHelp
                display-content="用于在MRP计算后赋值默认的采购/生产部门."
              />
            </template>
            <OrgsetTreeSelect
              v-model="form.itemPurchase.prodOrgCode"
              :has-priv="false"
            />
          </el-form-item>
          <el-form-item label="销售价" prop="busMainData.salePrice">
            <el-input-number
              v-model.number="form.busMainData.salePrice"
              :controls="false"
              :precision="6"
              :min="0"
              size="mini"
            />
          </el-form-item>
          <el-form-item label="会员价" prop="busMainData.vipSalePrice">
            <el-input-number
              v-model.number="form.busMainData.vipSalePrice"
              :controls="false"
              :precision="6"
              :min="0"
              size="mini"
            />
          </el-form-item>
          <el-form-item label="批发价" prop="busMainData.batchSalePrice">
            <el-input-number
              v-model.number="form.busMainData.batchSalePrice"
              :controls="false"
              :precision="6"
              :min="0"
              size="mini"
            />
          </el-form-item>
          <!-- <el-form-item label="采购单位" prop="itemPurchase.purUnit">
            <el-select v-model="form.itemPurchase.purUnit" filterable clearable placeholder="采购单位">
              <el-option
                v-for="(item) in dicts.item_unit"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"/>
            </el-select>
          </el-form-item> -->
        </el-tab-pane>
        <el-tab-pane name="relOtherCpyTab" label="关联其它公司产品">
          <div v-if="form.busPageInfo.editable" class="crud-opts">
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="doSelectRefItem"
              >选择物料</el-button
            >
            <el-button
              class="filter-item"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="doDeleteRefItem"
              >删除</el-button
            >
            <base-other-item-select-list
              ref="baseOtherItemSelectList"
              :sup_this="sup_this"
              :multi-select="true"
              @itemSelectCallback="itemSelectCallback"
            />
          </div>
          <el-table
            :data="form.itemRefs"
            size="mini"
            stripe
            border
            max-height="400px"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="itemCode" label="物料编号" />
            <el-table-column
              label="物料名称"
              prop="itemName"
              show-overflow-tooltip
            />
            <el-table-column
              label="规格"
              prop="itemSpec"
              show-overflow-tooltip
            />
            <el-table-column label="库存单位">
              <template slot-scope="scope">
                <template v-for="item in dicts.item_unit">
                  <span
                    v-if="
                      scope.row.stockUnit &&
                      scope.row.stockUnit === item.dictCode
                    "
                    :key="item.id"
                    >{{ item.dictName }}</span
                  >
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="modal-footer">
      <module-extend
        :editable="form.busPageInfo.editable"
        :source-form-object="formObject"
        :form-apply-id="form.busExtend.formApplyId"
        module-bus-class="200008-001"
      />
      <el-button v-if="form.busPageInfo.editable" type="text" @click="cancel"
        >取消</el-button
      >
      <el-button
        v-permission="[
          'SYS_ADMIN',
          'COMMON_ADMIN',
          'BASEITEM_ALL',
          'BASEITEM_CREATE',
        ]"
        v-if="form.busPageInfo.editable"
        :loading="loading"
        type="primary"
        @click="doSave"
        >保存</el-button
      >
    </div>
    <storage-location-select-list
      ref="slSelectList"
      :multi-select="false"
      :warehouse-id="form.busMainData.warehouseId"
      @slSelectCallback="slSelectCallback"
    />
  </CustomDialog>
</template>

<script>
import baseItem from "@/api/base/BaseItem";
import ItemCategoryTreeSelect from "@/views/components/ItemCategoryTreeSelect";
import WarehouseTreeSelect from "@/views/base/warehouse/module/WarehouseTreeSelect";
import moduleExtend from "@/views/components/moduleExtend";
import ItemUnitRate from "./itemUnitRate";
import BaseOtherItemSelectList from "./baseOtherItemSelectList";
import CpyOrgSetSelectDialog from "@/views/components/CpyOrgSetSelectDialog";
import OrgsetTreeSelect from "@/views/components/OrgsetTreeSelect";
import StorageLocationSelectList from "@/views/base/warehouse/storageLocation/module/storageLocationSelectList";

export default {
  components: {
    StorageLocationSelectList,
    BaseOtherItemSelectList,
    ItemUnitRate,
    WarehouseTreeSelect,
    ItemCategoryTreeSelect,
    moduleExtend,
    OrgsetTreeSelect,
    CpyOrgSetSelectDialog,
  },
  dictTypes: ["item_lot_type", "item_type", "item_unit", "bus_price_cur"],
  props: {
    sup_this: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      isAdd: false,
      loading: false,
      formObject: this,
      style: "width: 184px",
      dialogInfo: {
        name: "baseItemMngFormDialog",
        title: "物料维护",
        fullScreen: false,
        width: 80,
        height: 90,
      },
      selectedDetailRows: [],
      form: {
        busMainData: {
          id: "",
          enableFlag: "Y",
          warehouseId: "-1",
        },
        itemPurchase: {
          id: "",
        },
        busExtend: {},
        busPageInfo: {},
      },
      rules: {
        "busMainData.itemName": [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        "busMainData.catId": [
          { required: true, message: "请选择物料类别", trigger: "blur" },
        ],
        "busMainData.itemCode": [
          { required: true, message: "请输入物料编码", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    maxItemCode: {
      get() {
        return this.form.busMainData.itemCode;
      },
      set(val) {
        this.form.busMainData.itemCode = val.toUpperCase();
      },
    },
  },
  methods: {
    cancel() {
      this.resetForm();
    },
    initDataOfBefore() {},
    displayDialog() {
      const { name } = this.dialogInfo;
      this.$nextTick(() => {
        this.$modal.show(name);
      });
    },
    hiddenDialog() {
      const { name } = this.dialogInfo;
      this.$nextTick(() => {
        this.$modal.hide(name);
      });
    },
    handleSelectionChange(val) {
      this.selectedDetailRows = val;
    },
    addData() {
      this.isAdd = true;
      const data = { paramBean: {} };
      baseItem
        .toAdd(data)
        .then((res) => {
          this.displayDialog();
          this.form = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    copyData(mainId) {
      this.isAdd = true;
      const data = { paramBean: { id: mainId } };
      baseItem
        .toCopy(data)
        .then((res) => {
          this.displayDialog();
          this.form = res.data;
          this.processAttachment(this.form.busMainData.oldMainId);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    viewMainData(id) {
      this.isAdd = false;
      const data = { paramBean: { id: id } };
      baseItem.viewMainData(data).then((res) => {
        this.displayDialog();
        this.form = res.data;
        this.processAttachment(this.form.busMainData.id);
      });
    },
    doSubmit() {
      this.doSingleSave(true);
    },
    doSave() {
      this.doSingleSave(false);
    },
    doSingleSave(isSubmit) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.formSubmit = isSubmit;
          this.loading = true;
          if (this.isAdd) {
            this.doAdd();
          } else {
            this.doEdit();
          }
        }
      });
    },
    doAdd() {
      baseItem
        .addOrEdit(this.form)
        .then((res) => {
          this.resetForm();
          this.loading = false;
          this.sup_this.init();
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    doEdit() {
      baseItem
        .addOrEdit(this.form)
        .then((res) => {
          this.resetForm();
          this.loading = false;
          this.sup_this.init();
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    resetForm() {
      this.hiddenDialog();
      this.$refs["form"].resetFields();
    },
    userSelectCallback(selectedRow, selectObj) {
      this.form.itemPurchase.purchaseUser = "";
      if (selectedRow) {
        this.form.itemPurchase.purchaseUser = selectedRow.userAccount;
      }
      selectObj.cancel();
    },
    customSupplySelectCallback(selectedRow, selectObj) {
      this.form.itemPurchase.supplyCpyCode = "";
      this.form.itemPurchase.supplyCpyName = "";
      if (selectedRow) {
        this.form.itemPurchase.supplyCpyCode = selectedRow.cpyCode;
        this.form.itemPurchase.supplyCpyName = selectedRow.cpyName;
      }
      selectObj.cancel();
    },
    orgSetSelectCallback(orgCode) {
      this.form.itemPurchase.supplyOrgCode = "";
      if (orgCode) {
        this.form.itemPurchase.supplyOrgCode = orgCode;
      }
    },
    processAttachment(mainId) {
      const attachmentList = this.form.attachmentList;
      attachmentList.forEach((attachment) => {
        // 附档加载
        const tmpFileList = [];
        if (attachment.attribute1 === "primary") {
          tmpFileList.push(attachment);
          setTimeout(() => {
            this.$refs.imageFileUpload.setFileList(tmpFileList);
          }, 200);
        }
      });
    },
    fileRemoveSuccess(file) {
      this.form.attachmentList = this.form.attachmentList.filter(
        (t) => t.uid !== file.uid
      );
    },
    imageFileUploadSuccess(sysAttachment) {
      sysAttachment.attribute1 = "primary";
      this.form.attachmentList = this.form.attachmentList.filter(
        (t) => t.attribute1 !== sysAttachment.attribute1
      );
      this.form.attachmentList.push(sysAttachment);
    },
    doSelectRefItem() {
      const _thisform = this.$refs.baseOtherItemSelectList;
      _thisform.initLoadData();
    },
    doDeleteRefItem() {
      let tmpDetails = this.form.itemRefs;
      this.selectedDetailRows.forEach((tmprow) => {
        tmpDetails = tmpDetails.filter(
          (vo) => vo.refItemId !== tmprow.refItemId
        );
      });
      this.form.itemRefs = tmpDetails;
    },
    itemSelectCallback(selectedRows, sourceObject) {
      const allKeys = [];
      this.form.itemRefs.forEach((tmprow) => {
        allKeys[tmprow.refItemId] = true;
      });
      selectedRows.forEach((tmprow) => {
        if (!allKeys[tmprow.id]) {
          const addRow = {};
          addRow.refItemId = tmprow.id;
          addRow.stockUnit = tmprow.stockUnit;
          addRow.itemCode = tmprow.itemCode;
          addRow.itemName = tmprow.itemName;
          addRow.itemSpec = tmprow.itemSpec;
          addRow.itemBrand = tmprow.itemBrand;
          this.form.itemRefs.push(addRow);
        }
      });
      sourceObject.cancel();
    },
    addItemUnitRate() {
      const _this = this.$refs.itemUnitRate;
      _this.dialog = true;
    },
    doSelectSl() {
      const _thisform = this.$refs.slSelectList;
      _thisform.initLoadData();
    },
    slSelectCallback(selectedRow, sourceObject, paramData) {
      this.form.busMainData.storelocationId = "";
      this.form.busMainData.storelocationName = "";
      if (selectedRow) {
        this.form.busMainData.storelocationId = selectedRow.id;
        this.form.busMainData.storelocationName = selectedRow.slName;
      }
      sourceObject.cancel();
    },
  },
};
</script>
